package com.bym.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bym.mall.entity.Shipping;
import com.bym.mall.enums.ResponseEnum;
import com.bym.mall.form.ShippingForm;
import com.bym.mall.mapper.ShippingMapper;
import com.bym.mall.service.IShippingService;
import com.bym.mall.utils.UserUtil;
import com.bym.mall.vo.ResponseVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bym
 * @since 2022-03-28
 */
@Service
public class ShippingServiceImpl extends ServiceImpl<ShippingMapper, Shipping> implements IShippingService {

    @Resource
    private ShippingMapper shippingMapper;

    @Override
    public ResponseVo add(ShippingForm form) {
        Shipping shipping = new Shipping();
        shipping.setUserId(UserUtil.getUser().getId());
        BeanUtil.copyProperties(form, shipping);

        int row = shippingMapper.insert(shipping);
        if (row == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("shippingId", shipping.getId());

        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo delete(Integer shippingId) {
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserUtil.getUser().getId());
        queryWrapper.eq("id", shippingId);

        int row = shippingMapper.delete(queryWrapper);
        if (row == 0) {
            return ResponseVo.error(ResponseEnum.DELETE_SHIPPING_FAIL);
        }

        return ResponseVo.success();
    }

    @Override
    public ResponseVo update(Integer shippingId, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtil.copyProperties(form, shipping);
        shipping.setUserId(UserUtil.getUser().getId());
        shipping.setId(shippingId);

        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserUtil.getUser().getId());
        queryWrapper.eq("id", shippingId);

        int row = shippingMapper.update(shipping, queryWrapper);
        if (row == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }

        return ResponseVo.success();
    }

    @Override
    public ResponseVo list(Integer pageNum, Integer pageSize) {
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserUtil.getUser().getId());
        List<Shipping> shippingList = shippingMapper.selectList(queryWrapper);

        return ResponseVo.success(shippingList);
    }
}
